import { Component } from "react";
import * as echarts from "echarts";
import { random, cloneDeep, isEqual } from "lodash";
// 1. 初始化echarts图表实例
// 2. 更改图表配置
class App extends Component {
    state = {
        count: 0,
        option: {
            title: { text: "ECharts 入门示例" },
            tooltip: {},
            xAxis: {
                data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"],
            },
            yAxis: {},
            series: [
                {
                    name: "销量",
                    type: "bar",
                    data: [5, 20, 36, 10, 10, 20],
                },
            ],
        },
        myChart: null,
    };
    componentDidMount() {
        const myChart = echarts.init(this.refs.chart);
        this.setState(
            () => {
                return {
                    myChart,
                };
            },
            () => {
                window.addEventListener("resize", this.handleResize); // 并不是调用
                this.setChartOption(); // 调用
            }
        );
    }
    componentDidUpdate(prevProps, prevState) {
        if (
            !isEqual(
                this.state.option.series[0].data,
                prevState.option.series[0].data
            )
        ) {
            this.setChartOption();
        }
    }
    componentWillUnmount() {
        window.removeEventListener("resize", this.handleResize); // 并不是调用
        this.state.myChart.dispose(); //销毁echarts实例
    }
    handleResize = () => {
        this.state.myChart.resize();
    };
    setChartOption() {
        this.state.myChart.setOption(this.state.option);
    }
    render() {
        return (
            <div>
                <p>{this.state.count}</p>
                <div ref="chart" style={{ width: "40vw", height: 500 }}></div>
                <button
                    onClick={() => {
                        const data = [
                            random(0, 20),
                            random(0, 20),
                            random(0, 20),
                            random(0, 20),
                            random(0, 20),
                            random(0, 20),
                        ];
                        let newOption = cloneDeep(this.state.option);
                        newOption.series[0].data = data;
                        this.setState({
                            option: newOption,
                        });
                    }}>
                    修改图表数据
                </button>
                <button
                    onClick={() => {
                        this.setState({
                            count: this.state.count + 1,
                        });
                    }}>
                    修改count
                </button>
            </div>
        );
    }
}
export default App;
